package com.ruoyi.ky450.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.TargetClassEnum;
import com.ruoyi.common.enums.TreeFixedFacilityEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.ky450.domain.*;
import com.ruoyi.ky450.dto.*;
import com.ruoyi.ky450.mapper.*;
import com.ruoyi.ky450.service.*;
import com.ruoyi.ky450.vo.TreeDataVo;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 目标基本信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-16
 */
@Service
public class TargetBaseInfoServiceImpl extends ServiceImpl<TargetBaseInfoMapper, TargetBaseInfo> implements ITargetBaseInfoService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TargetBaseInfoMapper targetBaseInfoMapper;

    @Autowired
    private ITargetCategoryService targetCategoryService;

    @Autowired
    private IFixedFacilityElementInfoService fixedFacilityElementInfoService;

    @Autowired
    private IEquipBaseInfoService equipBaseInfoService;

    @Autowired
    private ITargetAttachmentService targetAttachmentService;

    @Autowired
    private TargetCategoryMapper targetCategoryMapper;

    @Autowired
    private FixedFacilityElementInfoMapper facilityElementInfoMapper;

    @Autowired
    private EquipRadarMapper radarMapper;

    @Autowired
    private EquipMissileMapper missileMapper;

    @Autowired
    private EquipAircraftMapper aircraftMapper;

    @Autowired
    private EquipArmoredVehicleMapper armoredVehicleMapper;

    @Autowired
    private EquipCannonMapper cannonMapper;

    @Autowired
    private EquipShipMapper shipMapper;

    /**
     * 查询目标基本信息
     *
     * @param id 目标基本信息主键
     * @return 目标基本信息
     */
    @Override
    public TargetBaseInfo selectTargetBaseInfoById(Long id) {
        //        bean.setTargetCategoryName(targetCategoryService.getNameById(bean.getTargetCategoryId()));
        return targetBaseInfoMapper.selectById(id);
    }

    /**
     * 查询目标基本信息列表
     *
     * @param targetBaseInfo 目标基本信息
     * @return 目标基本信息
     */
    @Override
    public List<TargetBaseInfo> selectTargetBaseInfoList(TargetBaseInfo targetBaseInfo) {
        QueryWrapper<TargetBaseInfo> queryWrapper = buildQueryTargetBaseInfo(targetBaseInfo);
        return targetBaseInfoMapper.selectList(queryWrapper);
    }

    /**
     * 新增目标基本信息
     *
     * @param targetBaseInfo 目标基本信息
     * @return 结果
     */
    @Override
    public int insertTargetBaseInfo(TargetBaseInfo targetBaseInfo) {
        return targetBaseInfoMapper.insertTargetBaseInfo(targetBaseInfo);
    }

    /**
     * 修改目标基本信息
     *
     * @param targetBaseInfo 目标基本信息
     * @return 结果
     */
    @Override
    public int updateTargetBaseInfo(TargetBaseInfo targetBaseInfo) {
        return targetBaseInfoMapper.updateTargetBaseInfo(targetBaseInfo);
    }

    /**
     * 批量删除目标基本信息
     *
     * @param ids 需要删除的目标基本信息主键
     * @return 结果
     */
    @Override
    public int deleteTargetBaseInfoByIds(Integer[] ids) {
        return targetBaseInfoMapper.deleteTargetBaseInfoByIds(ids);
    }

    /**
     * 删除目标基本信息信息
     *
     * @param id 目标基本信息主键
     * @return 结果
     */
    @Override
    public int deleteTargetBaseInfoById(Long id) {
        return targetBaseInfoMapper.deleteTargetBaseInfoById(id);
    }

    @Override
    public List<TreeDataVo> fixedFacilityListTree(TreeCommonCondition condition) {
        List<TreeDataVo> resultList = Lists.newArrayList();
        //根据关键字查询数据列表
        QueryWrapper<TargetBaseInfo> wrapper = new QueryWrapper<>();
        //根据关键字查询
        if (StringUtils.isNotBlank(condition.getWords())) {
            wrapper.like("target_name", condition.getWords());
        }
        wrapper.eq("target_class", TargetClassEnum.FIXED_FACILITY.getCode());
        List<TargetBaseInfo> list = list(wrapper);

        if (!CollectionUtils.isEmpty(list)) {
            //用【所属国家】进行分组
            Map<String, List<TargetBaseInfo>> dataMap = list.stream().collect(Collectors.groupingBy(TargetBaseInfo::getCountryAffiliation));
            for (Map.Entry<String, List<TargetBaseInfo>> entry : dataMap.entrySet()) {
                String key = entry.getKey();
                List<TargetBaseInfo> value = entry.getValue();
                TreeDataVo vo = new TreeDataVo(null, key, TreeFixedFacilityEnum.DATA_0.getCode());
                List<TreeDataVo> children = Lists.newArrayList();
                //用【目标类别id】进行分组
                Map<Long, List<TargetBaseInfo>> dataMap2 = new HashMap<>();
//                        value.stream().collect(Collectors.groupingBy(TargetBaseInfo::getTargetCategoryId));
                for (Map.Entry<Long, List<TargetBaseInfo>> entry2 : dataMap2.entrySet()) {
                    Long key2 = entry2.getKey();
                    String categoryName = targetCategoryService.getNameById(key2);
                    List<TargetBaseInfo> value2 = entry2.getValue();
                    TreeDataVo vo2 = new TreeDataVo(null, categoryName, TreeFixedFacilityEnum.DATA_1.getCode());

                    List<TreeDataVo> children2 = Lists.newArrayList();
                    for (TargetBaseInfo info2 : value2) {
                        TreeDataVo vo3 = new TreeDataVo(info2.getId(), info2.getTargetName(), TreeFixedFacilityEnum.DATA_2.getCode());
                        children2.add(vo3);
                    }
                    vo2.setChildren(children2);
                    children.add(vo2);
                }

                vo.setChildren(children);
                resultList.add(vo);
            }
        }
        return resultList;
    }

    @Override
    public List<TreeDataVo> equipListTree(TreeCommonCondition condition) {
        List<TreeDataVo> resultList = Lists.newArrayList();
        QueryWrapper<TargetCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("category_name", TargetClassEnum.EQUIP.getDesc());
        wrapper.eq("parent_id", Constants.HIGHEST_CODE);
        TargetCategory firstBean = targetCategoryService.getOne(wrapper);
        if (firstBean != null) {
            List<TargetCategory> list = getChildrenListDB(firstBean.getId());
            //根据主键id去重
            list = list.stream()
                    .collect(Collectors.collectingAndThen(
                            Collectors.toMap(
                                    TargetCategory::getId,  // 以 id 作为键
                                    entity -> entity, // 以实体作为值
                                    (existing, replacement) -> existing, // 如果键已存在，保留现有的元素
                                    () -> new java.util.LinkedHashMap<>() // 使用 LinkedHashMap 来保持插入顺序
                            ),
                            map -> new ArrayList<>(map.values()) // 将 map 的值提取到新的 ArrayList 中
                    ));

            if (!CollectionUtils.isEmpty(list)) {
                //用parentId进行分组
                Map<Long, List<TargetCategory>> dataMap = list.stream().collect(Collectors.groupingBy(TargetCategory::getParentId));
                //查询 parentId=firstBean.getId() 的集合
                List<TargetCategory> topList = getTopList(dataMap, firstBean.getId());
                if (!CollectionUtils.isEmpty(topList)) {
                    for (TargetCategory bean : topList) {
                        TreeDataVo vo = new TreeDataVo(bean.getId(), bean.getCategoryName(), TreeFixedFacilityEnum.DATA_1.getCode());
                        List<TreeDataVo> childrenList = this.getChildrenList(bean.getId(), dataMap, condition);
                        if (CollectionUtils.isEmpty(childrenList)) {
                            childrenList = this.getTargetBaseInfoList(bean.getId(), condition);
                        }
                        vo.setChildren(childrenList);
                        resultList.add(vo);
                    }
                }
            }
        }
        return resultList;
    }

    @Override
    public TargetElementInfoDto getFixedFacility(Long id) {
        TargetBaseInfo targetBaseInfo = targetBaseInfoMapper.selectById(id);
        TargetElementInfoDto targetElementInfoDto = new TargetElementInfoDto();
        BeanUtils.copyProperties(targetBaseInfo, targetElementInfoDto);
        FixedFacilityElementInfo infoId = fixedFacilityElementInfoService.getFixedFacilityByTBInfoId(id);
        BeanUtils.copyProperties(infoId, targetElementInfoDto);
        return targetElementInfoDto;
    }

    @Override
    public EquipAllInfoDto getEquip(Long id) {
        TargetBaseInfo targetBaseInfo = targetBaseInfoMapper.selectById(id);
        if (targetBaseInfo != null) {
            EquipAllInfoDto allInfoDto = new EquipAllInfoDto();
            BeanUtils.copyProperties(targetBaseInfo, allInfoDto);
            EquipBaseInfo equipBaseInfo = equipBaseInfoService.selectEquipAllInfoById(targetBaseInfo.getTargetClass()
                    , targetBaseInfo.getTargetId());
            BeanUtils.copyProperties(equipBaseInfo, allInfoDto);
            return allInfoDto;
        } else {
            throw new ServiceException("当前装备信息不存在：" + id);
        }
    }

    @Override
    public List<TargetAttachment> getTargetAttachment(TargetAttachmentCondition condition) {
        QueryWrapper<TargetAttachment> wrapper = new QueryWrapper<>();
        if (condition.getTargetId() != null) {
            wrapper.eq("target_base_info_id", condition.getTargetId());
        }
        if (condition.getAttachmentType() != null) {
            wrapper.eq("attachment_type", condition.getAttachmentType());
        }
        return targetAttachmentService.list(wrapper);
    }

    @Override
    public int addTargetCategory(TargetCategory category) {
        redisCache.deleteObject("targetTree" + category.getType());
        return targetCategoryService.insertTargetCategory(category);
    }

    @Override
    public List<Tree<String>> getCacheTrees(TreeCommonCondition condition) {
        List<Tree<String>> targetTree = redisCache.getCacheObject("targetTree" + condition.getType());
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(targetTree)) {
            return targetTree;
        }
        List<Tree<String>> treeList = getTrees(condition.getType());
        redisCache.setCacheObject("targetTree" + condition.getType(), treeList);
        return treeList;
    }

    @Override
    public int editTargetCategory(TargetCategory category) {
        redisCache.deleteObject("targetTree" + category.getType());
        return targetCategoryService.updateTargetCategory(category);
    }

    @Override
    public Long insertTargetFacility(TargetElementInfoDto targetElementInfoDto) {
        if (StringUtils.isNotBlank(targetElementInfoDto.getTargetName())) {
            List<TargetBaseInfo> list = targetBaseInfoMapper.selectList(new QueryWrapper<TargetBaseInfo>()
                    .eq("target_name", targetElementInfoDto.getTargetName()));
            if (!CollectionUtils.isEmpty(list)) {
                throw new ServiceException("目标名称已存在！");
            }
        }
        FixedFacilityElementInfo fixedFacilityElementInfo = new FixedFacilityElementInfo();
        BeanUtils.copyProperties(targetElementInfoDto, fixedFacilityElementInfo);
        TargetBaseInfo targetBaseInfo = new TargetBaseInfo();
        BeanUtils.copyProperties(targetElementInfoDto, targetBaseInfo);
        targetBaseInfo.setTargetClass(6);
        targetBaseInfo.setTargetType(targetElementInfoDto.getTargetType());
        targetBaseInfoMapper.insert(targetBaseInfo);
        fixedFacilityElementInfo.setTargetBaseInfoId(targetBaseInfo.getId());
        facilityElementInfoMapper.insert(fixedFacilityElementInfo);
        TargetCategory targetCategory = new TargetCategory();
        targetCategory.setCategoryName(targetBaseInfo.getTargetName());
        targetCategory.setType(1);
        targetCategory.setParentId(targetElementInfoDto.getParentId());
        Integer selectCount = getCategoryLevel(targetElementInfoDto.getParentId());
        targetCategory.setLevel(selectCount);
        targetCategory.setInfoId(targetBaseInfo.getId());
        addTargetCategory(targetCategory);
        return targetBaseInfo.getId();
    }

    @Override
    public Long insertTargetEquip(EquipAllInfoDto equipBaseInfo) {
        if (equipBaseInfo.getParentId() == null) {
            Long category = getCategoryByEquip(equipBaseInfo);
            equipBaseInfo.setParentId(category);
        }
        int info = equipBaseInfoService.insertEquipBaseInfo(equipBaseInfo);
        if (info < 1) {
            throw new ServiceException("新增失败");
        }
        TargetBaseInfo targetBaseInfo = new TargetBaseInfo();
        BeanUtils.copyProperties(equipBaseInfo, targetBaseInfo);
        targetBaseInfo.setTargetClass(equipBaseInfo.getTargetClass());
        targetBaseInfo.setTargetType(equipBaseInfo.getTargetType());
        targetBaseInfo.setTargetId(equipBaseInfo.getEquipBaseInfoId());
        targetBaseInfoMapper.insert(targetBaseInfo);
        Map<String, Object> map = BeanUtil.beanToMap(equipBaseInfo.getTAti());
        map.put("equipBaseInfoId", equipBaseInfo.getEquipBaseInfoId());
        switch (equipBaseInfo.getTargetClass()) {
            case 0:
                EquipRadar equipRadar = BeanUtil.toBean(map, EquipRadar.class);
                radarMapper.insert(equipRadar);
                break;
            case 1:
                EquipMissile equipMissile = BeanUtil.toBean(map, EquipMissile.class);
                missileMapper.insert(equipMissile);
                break;
            case 2:
                EquipAircraft aircraft = BeanUtil.toBean(map, EquipAircraft.class);
                aircraftMapper.insert(aircraft);
                break;
            case 3:
                EquipShip equipShip = BeanUtil.toBean(map, EquipShip.class);
                shipMapper.insert(equipShip);
                break;
            case 4:
                EquipCannon cannon = BeanUtil.toBean(map, EquipCannon.class);
                cannonMapper.insert(cannon);
                break;
            default:
                EquipArmoredVehicle armoredVehicle = BeanUtil.toBean(map, EquipArmoredVehicle.class);
                armoredVehicleMapper.insert(armoredVehicle);
                break;
        }
        TargetCategory targetCategory = new TargetCategory();
        targetCategory.setCategoryName(targetBaseInfo.getTargetName());
        targetCategory.setType(2);
        targetCategory.setParentId(equipBaseInfo.getParentId());
        targetCategory.setInfoId(targetBaseInfo.getId());
        Integer selectCount = getCategoryLevel(equipBaseInfo.getParentId());
        targetCategory.setLevel(selectCount);
        addTargetCategory(targetCategory);
        return targetBaseInfo.getId();
    }

    @Override
    public int delTarget(Long id) {
        // 查询当前节点
        TargetCategory node = targetCategoryMapper.selectById(id);
        if (node == null) {
            // 如果没有找到该节点，返回 null
            return 0;
        }
        deleteDescendants(node, null);
        targetCategoryMapper.deleteById(node.getId());
        return redisCache.deleteObject("targetTree" + node.getType()) ? 1 : 0;
    }

    @Override
    public int editTargetFacility(TargetElementInfoDto targetElementInfoDto) {
        TargetBaseInfo targetBaseInfo = targetBaseInfoMapper.selectOne(new QueryWrapper<TargetBaseInfo>()
                .eq("target_name", targetElementInfoDto.getTargetName()));
        if (targetBaseInfo != null && !targetElementInfoDto.getId().equals(targetBaseInfo.getId())) {
            throw new ServiceException("当前目标名称已存在，请修改名称");
        }else {
            targetBaseInfo = targetBaseInfoMapper.selectById(targetElementInfoDto.getId());
        }
        BeanUtils.copyProperties(targetElementInfoDto, targetBaseInfo);
        targetBaseInfoMapper.updateById(targetBaseInfo);
        FixedFacilityElementInfo fixedFacilityElementInfo = new FixedFacilityElementInfo();
        BeanUtils.copyProperties(targetElementInfoDto, fixedFacilityElementInfo);
        fixedFacilityElementInfo.setUpdateTime(new Date());
        return facilityElementInfoMapper.updateById(fixedFacilityElementInfo);
    }

    @Override
    public boolean editTargetEquip(EquipAllInfoDto equipBaseInfo) {
        TargetBaseInfo targetBaseInfo = new TargetBaseInfo();
        BeanUtils.copyProperties(equipBaseInfo, targetBaseInfo);
        targetBaseInfoMapper.updateById(targetBaseInfo);
        EquipBaseInfo baseInfo = new EquipBaseInfo();
        BeanUtils.copyProperties(equipBaseInfo, baseInfo);
        baseInfo.setUpdateTime(new Date());
        baseInfo.setEquipBaseInfoId(targetBaseInfo.getTargetId());
        boolean info = equipBaseInfoService.updateById(baseInfo);
        if (!info) {
            return false;
        }
        Map<String, Object> map = BeanUtil.beanToMap(equipBaseInfo.getTAti());
        map.put("equipBaseInfoId", baseInfo.getEquipBaseInfoId());
        //
        switch (targetBaseInfo.getTargetClass()) {
            case 0:
                EquipRadar equipRadar = BeanUtil.toBean(map, EquipRadar.class);
                radarMapper.updateById(equipRadar);
                break;
            case 1:
                EquipMissile equipMissile = BeanUtil.toBean(map, EquipMissile.class);
                missileMapper.updateById(equipMissile);
                break;
            case 2:
                EquipAircraft aircraft = BeanUtil.toBean(map, EquipAircraft.class);
                aircraftMapper.updateById(aircraft);
                break;
            case 3:
                EquipShip equipShip = BeanUtil.toBean(map, EquipShip.class);
                shipMapper.updateById(equipShip);
                break;
            case 4:
                EquipCannon cannon = BeanUtil.toBean(map, EquipCannon.class);
                cannonMapper.updateById(cannon);
                break;
            default:
                EquipArmoredVehicle armoredVehicle = BeanUtil.toBean(map, EquipArmoredVehicle.class);
                armoredVehicleMapper.updateById(armoredVehicle);
                break;
        }
        return true;
    }

    @Override
    public int insertTargetFile(TargetAttachment attachment) {
        String path = RuoYiConfig.getLocalPath(attachment.getAttachmentPath());
        File file = new File(path);
        long size = FileUtil.size(file);
        attachment.setAttachmentSize(size);
        attachment.setAttachmentName(file.getName());
        return targetAttachmentService.insertTargetAttachment(attachment);
    }

    @Override
    public int delTargetFile(Long id) {
        TargetAttachment attachment = targetAttachmentService.getById(id);
        FileUtil.del(RuoYiConfig.getLocalPath(attachment.getAttachmentPath()));
        return targetAttachmentService.deleteTargetAttachmentById(id);
    }

    @Override
    public Long getCategoryByTarget(TargetElementInfoDto targetElementInfoDto) {
        return setTargetCategory(1, targetElementInfoDto.getCountryAffiliation(), targetElementInfoDto.getTargetType());
    }

    @Override
    public Long getCategoryByEquip(EquipAllInfoDto equipAllInfoDto) {
        return setTargetCategory(2, equipAllInfoDto.getTargetClassify(), equipAllInfoDto.getTargetType());
    }

    @Override
    public String importFacility(List<TargetElementInfoDto> list, boolean updateSupport) {
        if (com.ruoyi.common.utils.StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int[] num = {0, 0};
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TargetElementInfoDto elementInfoDto : list) {
            try {
                // 验证是否存在这个用户
                if (StringUtils.isNotBlank(elementInfoDto.getTargetName())) {
                    TargetBaseInfo baseInfo = targetBaseInfoMapper.selectOne(new QueryWrapper<TargetBaseInfo>()
                            .eq("target_name", elementInfoDto.getTargetName()));
                    if (baseInfo != null) {
                        editTargetFacility(elementInfoDto);
                        num[0]++;
                        successMsg.append("<br/>").append(num[0]).append("、目标： ").append(elementInfoDto.getTargetName()).append(" 更新成功");
                    } else {
                        insertTargetFacility(elementInfoDto);
                        num[0]++;
                        successMsg.append("<br/>").append(num[0]).append("、目标： ").append(elementInfoDto.getTargetName()).append(" 导入成功");
                    }
                }
            } catch (Exception e) {
                num[1]++;
                String msg = "<br/>" + num[1] + "、目标： " + elementInfoDto.getTargetName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        return buildImport(successMsg, failureMsg, num);
    }

    @Override
    public List<TargetElementInfoDto> exportFacilityData(TargetBaseInfo baseInfo) {
        QueryWrapper<TargetBaseInfo> wrapper = buildQueryTargetBaseInfo(baseInfo);
        List<TargetBaseInfo> baseInfos = targetBaseInfoMapper.selectList(wrapper);
        return baseInfos.stream().map(var -> getFixedFacility(var.getId())).collect(Collectors.toList());
    }

    @Override
    public List<EquipAircraftDto> exportDataAir(TargetBaseInfo baseInfo) {
        List<TargetBaseInfo> baseInfos = getTargetBaseInfoDto(baseInfo);
        return baseInfos.stream().map(info -> {
            EquipAllInfoDto equip = getEquip(info.getId());
            EquipAircraft equipAircraft = aircraftMapper.selectById(info.getTargetId());
            EquipAircraftDto aircraftDto = new EquipAircraftDto();
            BeanUtils.copyProperties(equip, aircraftDto);
            BeanUtils.copyProperties(equipAircraft, aircraftDto);
            return aircraftDto;
        }).collect(Collectors.toList());
    }

    @Override
    public List<EquipArmoredVehicleDto> exportDataArmored(TargetBaseInfo baseInfo) {
        List<TargetBaseInfo> baseInfos = getTargetBaseInfoDto(baseInfo);
        return baseInfos.stream().map(info -> {
            EquipAllInfoDto equip = getEquip(info.getId());
            EquipArmoredVehicle equipAircraft = armoredVehicleMapper.selectById(info.getTargetId());
            EquipArmoredVehicleDto armoredVehicleDto = new EquipArmoredVehicleDto();
            BeanUtils.copyProperties(equip, armoredVehicleDto);
            BeanUtils.copyProperties(equipAircraft, armoredVehicleDto);
            return armoredVehicleDto;
        }).collect(Collectors.toList());
    }

    @Override
    public List<EquipCannonDto> exportDataCannon(TargetBaseInfo baseInfo) {
        List<TargetBaseInfo> baseInfos = getTargetBaseInfoDto(baseInfo);
        return baseInfos.stream().map(info -> {
            EquipAllInfoDto equip = getEquip(info.getId());
            EquipCannon cannon = cannonMapper.selectById(info.getTargetId());
            EquipCannonDto cannonDto = new EquipCannonDto();
            BeanUtils.copyProperties(equip, cannonDto);
            BeanUtils.copyProperties(cannon, cannonDto);
            return cannonDto;
        }).collect(Collectors.toList());
    }

    @Override
    public List<EquipMissileDto> exportDataMissile(TargetBaseInfo baseInfo) {
        List<TargetBaseInfo> baseInfos = getTargetBaseInfoDto(baseInfo);
        return baseInfos.stream().map(info -> {
            EquipAllInfoDto equip = getEquip(info.getId());
            EquipMissile missile = missileMapper.selectById(info.getTargetId());
            EquipMissileDto missileDto = new EquipMissileDto();
            BeanUtils.copyProperties(equip, missileDto);
            BeanUtils.copyProperties(missile, missileDto);
            return missileDto;
        }).collect(Collectors.toList());
    }

    @Override
    public List<EquipRadarDto> exportDataRadar(TargetBaseInfo baseInfo) {
        List<TargetBaseInfo> baseInfos = getTargetBaseInfoDto(baseInfo);
        return baseInfos.stream().map(info -> {
            EquipAllInfoDto equip = getEquip(info.getId());
            EquipRadar radar = radarMapper.selectById(info.getTargetId());
            EquipRadarDto radarDto = new EquipRadarDto();
            BeanUtils.copyProperties(equip, radarDto);
            BeanUtils.copyProperties(radar, radarDto);
            return radarDto;
        }).collect(Collectors.toList());
    }

    @Override
    public List<EquipShipDto> exportDataShip(TargetBaseInfo baseInfo) {
        List<TargetBaseInfo> baseInfos = getTargetBaseInfoDto(baseInfo);
        return baseInfos.stream().map(info -> {
            EquipAllInfoDto equip = getEquip(info.getId());
            EquipShip ship = shipMapper.selectById(info.getTargetId());
            EquipShipDto shipDto = new EquipShipDto();
            BeanUtils.copyProperties(equip, shipDto);
            BeanUtils.copyProperties(ship, shipDto);
            return shipDto;
        }).collect(Collectors.toList());
    }

    @Override
    public String importDataArmored(List<EquipArmoredVehicleDto> list, boolean updateSupport) {
        importIsEmpty(list);
        int[] num = {0, 0};
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (EquipArmoredVehicleDto infoDto : list) {
            EquipArmoredVehicle armoredVehicle = new EquipArmoredVehicle();
            BeanUtils.copyProperties(infoDto, armoredVehicle);
            infoDto.setTAti(armoredVehicle);
            // 0:雷达 1:导弹 2:飞机 3:舰船 4:火炮 5:装甲车 6:固定设施
            infoDto.setTargetClass(5);
            importEquip(num, successMsg, failureMsg, infoDto);
        }
        return buildImport(successMsg, failureMsg, num);
    }

    @Override
    public String importDataCannon(List<EquipCannonDto> list, boolean updateSupport) {
        importIsEmpty(list);
        int[] num = {0, 0};
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (EquipCannonDto infoDto : list) {
            EquipCannonDto info = new EquipCannonDto();
            BeanUtils.copyProperties(infoDto, info);
            // 0:雷达 1:导弹 2:飞机 3:舰船 4:火炮 5:装甲车 6:固定设施
            infoDto.setTargetClass(4);
            infoDto.setTAti(info);
            importEquip(num, successMsg, failureMsg, infoDto);
        }
        return buildImport(successMsg, failureMsg, num);
    }

    @Override
    public String importDataMissile(List<EquipMissileDto> list, boolean updateSupport) {
        importIsEmpty(list);
        int[] num = {0, 0};
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (EquipMissileDto infoDto : list) {
            EquipMissileDto info = new EquipMissileDto();
            BeanUtils.copyProperties(infoDto, info);
            // 0:雷达 1:导弹 2:飞机 3:舰船 4:火炮 5:装甲车 6:固定设施
            infoDto.setTargetClass(1);
            infoDto.setTAti(info);
            importEquip(num, successMsg, failureMsg, infoDto);
        }
        return buildImport(successMsg, failureMsg, num);
    }

    @Override
    public String importDataRadar(List<EquipRadarDto> list, boolean updateSupport) {
        importIsEmpty(list);
        int[] num = {0, 0};
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (EquipRadarDto infoDto : list) {
            EquipRadarDto info = new EquipRadarDto();
            BeanUtils.copyProperties(infoDto, info);
            infoDto.setTargetClass(0);
            infoDto.setTAti(info);
            importEquip(num, successMsg, failureMsg, infoDto);
        }
        return buildImport(successMsg, failureMsg, num);
    }

    @Override
    public String importDataShip(List<EquipShipDto> list, boolean updateSupport) {
        importIsEmpty(list);
        int[] num = {0, 0};
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (EquipShipDto infoDto : list) {
            EquipShipDto info = new EquipShipDto();
            BeanUtils.copyProperties(infoDto, info);
            infoDto.setTargetClass(3);
            infoDto.setTAti(info);
            importEquip(num, successMsg, failureMsg, infoDto);
        }
        return buildImport(successMsg, failureMsg, num);
    }

    @Override
    public String importDataAir(List<EquipAircraftDto> list, boolean updateSupport) {
        importIsEmpty(list);
        int[] num = {0, 0};
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (EquipAircraftDto infoDto : list) {
            EquipAircraftDto info = new EquipAircraftDto();
            BeanUtils.copyProperties(infoDto, info);
            infoDto.setTAti(info);
            infoDto.setTargetClass(2);
            importEquip(num, successMsg, failureMsg, infoDto);
        }
        return buildImport(successMsg, failureMsg, num);
    }

    @Override
    public IPage<EquipAllInfoDto> selectEquipList(TargetBaseInfo targetBaseInfo) {
        QueryWrapper<TargetBaseInfo> wrapper = buildQueryTargetBaseInfo(targetBaseInfo);
        IPage<TargetBaseInfo> page = buildTargetBaseInfoPage(targetBaseInfo, wrapper);
        List<EquipAllInfoDto> equipList = page.getRecords().stream().map(var -> getEquip(var.getId())).collect(Collectors.toList());
        // 将查询结果转换为 Page<Equip> 类型
        IPage<EquipAllInfoDto> returnPage = new Page<>();
        returnPage.setRecords(equipList);
        returnPage.setTotal(page.getTotal());
        return returnPage;
    }

    @Override
    public int delTargetByTargetId(Long id) {
        // 查询当前节点
        TargetCategory category = new TargetCategory();
        category.setInfoId(id);
        QueryWrapper<TargetCategory> wrapper = buildQueryTargetCategory(category);
        TargetCategory node = targetCategoryMapper.selectOne(wrapper);
        if (node == null) {
            // 如果没有找到该节点，返回 null
            return 0;
        }
        return deleteTargetCategoryAndTarget(node.getId());
    }

    @Override
    public IPage<TargetElementInfoDto> selectTargetList(TargetBaseInfo targetBaseInfo) {
        QueryWrapper<TargetBaseInfo> wrapper = buildQueryTargetBaseInfo(targetBaseInfo);
        IPage<TargetBaseInfo> page = buildTargetBaseInfoPage(targetBaseInfo, wrapper);
        List<TargetElementInfoDto> list = page.getRecords().stream().map(var -> getFixedFacility(var.getId())).collect(Collectors.toList());
        // 将查询结果转换为 Page<Equip> 类型
        IPage<TargetElementInfoDto> returnPage = new Page<>();
        returnPage.setRecords(list);
        returnPage.setTotal(page.getTotal());
        return returnPage;
    }

    /**
     * 分页查询
     * @param baseInfo pageInfo
     * @return iPage
     */
    private IPage<TargetBaseInfo> buildTargetBaseInfoPage(TargetBaseInfo baseInfo, QueryWrapper<TargetBaseInfo> wrapper){
        IPage<TargetBaseInfo> page = new Page<>(baseInfo.getPageNum(), baseInfo.getPageSize());
        return targetBaseInfoMapper.selectPage(page,wrapper);
    }

    /**
     * 导入装备
     *
     * @param num        成功数量\失败数量
     * @param successMsg 成功信息
     * @param failureMsg 失败信息
     * @param infoDto    装备信息
     */
    private void importEquip(int[] num, StringBuilder successMsg, StringBuilder failureMsg,
                             EquipAllInfoDto infoDto) {
        try {
            // 验证是否存在这个用户
            if (StringUtils.isNotBlank(infoDto.getTargetName())) {
                TargetBaseInfo baseInfo = targetBaseInfoMapper.selectOne(new QueryWrapper<TargetBaseInfo>()
                        .eq("target_name", infoDto.getTargetName()));
                if (baseInfo != null) {
                    infoDto.setTargetId(baseInfo.getTargetId());
                    editTargetEquip(infoDto);
                    num[0]++;
                    successMsg.append("<br/>").append(num[0]).append("、目标： ").append(infoDto.getTargetName()).append(" 更新成功");
                } else {
                    insertTargetEquip(infoDto);
                    num[0]++;
                    successMsg.append("<br/>").append(num[0]).append("、目标： ").append(infoDto.getTargetName()).append(
                            " 导入成功");
                }
            }
        } catch (Exception e) {
            num[1]++;
            String msg = "<br/>" + num[1] + "、目标： " + infoDto.getTargetName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    /**
     * 判断导入数据集合是否为空
     *
     * @param list list
     */
    public void importIsEmpty(List<?> list) {
        if (com.ruoyi.common.utils.StringUtils.isEmpty(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
    }

    /**
     * 封装查询
     *
     * @param baseInfo queryInfo
     * @return list
     */
    public List<TargetBaseInfo> getTargetBaseInfoDto(TargetBaseInfo baseInfo) {
        QueryWrapper<TargetBaseInfo> wrapper = buildQueryTargetBaseInfo(baseInfo);
        return targetBaseInfoMapper.selectList(wrapper);
    }

    /**
     * 封装导入返回信息
     *
     * @param successMsg 成功
     * @param failureMsg 失败
     * @param num        成功数量/失败数量
     * @return string
     */
    private String buildImport(StringBuilder successMsg, StringBuilder failureMsg, int[] num) {
        if (num[1] > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + num[1] + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + num[0] + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 根据一级类型 二级类型查询数据
     *
     * @param type      1固定设施 2装备
     * @param firstName 一级分类
     * @param lastName  二级分类
     * @return id
     */
    private Long setTargetCategory(Integer type, String firstName, String lastName) {
        TargetCategory category = new TargetCategory();
        category.setType(type);
        category.setParentId(0L);
        category.setCategoryName(firstName);
        QueryWrapper<TargetCategory> wrapper = buildQueryTargetCategory(category);
        TargetCategory oneType = targetCategoryMapper.selectOne(wrapper);
        if (oneType != null) {
            category.setParentId(oneType.getId());
            category.setCategoryName(lastName);
            QueryWrapper<TargetCategory> typeWrapper = buildQueryTargetCategory(category);
            TargetCategory typeLast = targetCategoryMapper.selectOne(typeWrapper);
            if (typeLast == null) {
                Integer level = getCategoryLevel(oneType.getId());
                category.setLevel(level);
                targetCategoryMapper.insert(category);
                return category.getId();
            }
            return typeLast.getId();
        } else {
            Integer level = getCategoryLevel(0L);
            category.setLevel(level);
            targetCategoryMapper.insert(category);
            TargetCategory typeLast = new TargetCategory();
            typeLast.setType(type);
            typeLast.setLevel(0);
            typeLast.setParentId(category.getId());
            typeLast.setCategoryName(lastName);
            targetCategoryMapper.insert(typeLast);
            return typeLast.getId();
        }
    }

    /**
     * 查找所有子孙节点删除
     *
     * @param parentId 父Id
     */
    private void deleteDescendants(TargetCategory targetCategory, Long parentId) {
        List<TargetCategory> children = targetCategoryMapper.selectList(new QueryWrapper<TargetCategory>()
                .eq("parent_id", targetCategory.getId()));
        if (CollectionUtils.isEmpty(children)) {
            deleteTargetCategoryAndTarget(targetCategory.getId());
            return;
        }
        //递归删除子节点
        for (TargetCategory child : children) {
            deleteDescendants(child, targetCategory.getId());
        }
        //最后删除上级节点
        if (parentId != null) {
            deleteTargetCategoryAndTarget(parentId);
        }
    }

    /**
     * 根据节点id删除目标
     *
     * @param categoryId 节点id
     */
    private int deleteTargetCategoryAndTarget(Long categoryId) {
        TargetCategory targetCategory = targetCategoryMapper.selectById(categoryId);
        if (targetCategory.getInfoId() != null) {
            TargetBaseInfo targetBaseInfo = targetBaseInfoMapper.selectById(targetCategory.getInfoId());
            Long targetId = targetBaseInfo.getTargetId();
            //0:雷达 1:导弹 2:飞机 3:舰船 4:火炮 5:装甲车 6:固定设施
            if (targetBaseInfo.getTargetClass() == 6) {
                aircraftMapper.deleteById(targetId);
            } else {
                equipBaseInfoService.deleteEquipBaseInfoById(targetBaseInfo.getTargetClass(), targetId);
            }
            targetBaseInfoMapper.deleteById(targetBaseInfo.getId());
            //TODO 删除附件？
        }
        return targetCategoryMapper.deleteById(categoryId);
    }

    /**
     * 封装树结构列表
     *
     * @return list
     */
    public List<Tree<String>> getTrees(Integer type) {
        List<TargetCategory> targetTrees = targetCategoryMapper.selectList(new QueryWrapper<TargetCategory>()
                .eq("type", type));
        List<TreeNode<Long>> nodeList = new ArrayList<>();
        for (TargetCategory tree : targetTrees) {
            Map<String, Object> hashMap = new LinkedHashMap<>(2);
            if (StringUtils.isNotBlank(tree.getRemark())) {
                hashMap.put("note", tree.getRemark());
            }
            if (tree.getInfoId() != null) {
                TargetBaseInfo targetBaseInfo = targetBaseInfoMapper.selectById(tree.getInfoId());
                if (targetBaseInfo != null) {
                    hashMap.put("target_id", tree.getInfoId());
                    if (type == 1) {
                        hashMap.put("lon", targetBaseInfo.getLongitude());
                        hashMap.put("lat", targetBaseInfo.getLatitude());
                    }
                }
            }
            nodeList.add(new TreeNode<>(tree.getId(), tree.getParentId(), tree.getCategoryName(),
                    tree.getLevel()).setExtra(hashMap));
        }
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setWeightKey("order");
        treeNodeConfig.setIdKey("id");
        // 最大递归深度
        treeNodeConfig.setDeep(4);
        return TreeUtil.build(nodeList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(String.valueOf(treeNode.getId()));
                    tree.setParentId(String.valueOf(treeNode.getParentId()));
                    tree.setWeight(treeNode.getWeight());
                    tree.setName(treeNode.getName());
                    tree.putExtra("attributes", treeNode.getExtra());
                });
    }

    /**
     * 获取树结构排序
     *
     * @param parentId 父节点id
     * @return level
     */
    private Integer getCategoryLevel(Long parentId) {
        Integer selectCount = targetCategoryMapper.selectCount(new QueryWrapper<TargetCategory>()
                .eq("parent_id", parentId));
        return ++selectCount;
    }

    /**
     * 构建查询条件
     *
     * @param targetCategory 目标信息
     * @return 查询条件
     */
    public QueryWrapper<TargetCategory> buildQueryTargetCategory(TargetCategory targetCategory) {
        QueryWrapper<TargetCategory> queryWrapper = new QueryWrapper<>();
        if (targetCategory.getId() != null) {
            queryWrapper.eq("id", targetCategory.getId());
        }
        if (targetCategory.getParentId() != null) {
            queryWrapper.eq("parent_id", targetCategory.getParentId());
        }
        if (targetCategory.getCategoryName() != null) {
            queryWrapper.like("category_name", targetCategory.getCategoryName());
        }
        if (targetCategory.getType() != null) {
            queryWrapper.eq("type", targetCategory.getType());
        }
        if (targetCategory.getInfoId() != null) {
            queryWrapper.eq("info_id", targetCategory.getInfoId());
        }
        return queryWrapper;
    }

    /**
     * 查询目标基本信息 封装QueryWrapper
     *
     * @param targetBaseInfo 目标基本信息
     * @return QueryWrapper
     */
    public QueryWrapper<TargetBaseInfo> buildQueryTargetBaseInfo(TargetBaseInfo targetBaseInfo) {
        QueryWrapper<TargetBaseInfo> queryWrapper = new QueryWrapper<>();
        if (targetBaseInfo.getId() != null) {
            queryWrapper.eq("id", targetBaseInfo.getId());
        }
        if (targetBaseInfo.getTargetId() != null) {
            queryWrapper.eq("target_id", targetBaseInfo.getTargetId());
        }
        if (targetBaseInfo.getTargetClass() != null) {
            queryWrapper.eq("target_class", targetBaseInfo.getTargetClass());
        }
        if (StringUtils.isNotBlank(targetBaseInfo.getTargetName())) {
            queryWrapper.like("target_name", targetBaseInfo.getTargetName());
        }
        if (StringUtils.isNotBlank(targetBaseInfo.getTargetNickname())) {
            queryWrapper.like("target_nick_name", targetBaseInfo.getTargetNickname());
        }
        if (StringUtils.isNotBlank(targetBaseInfo.getCountryAffiliation())) {
            queryWrapper.eq("country_affiliation", targetBaseInfo.getCountryAffiliation());
        }
        return queryWrapper;
    }

    @Deprecated
    private List<TargetCategory> getTopList(Map<Long, List<TargetCategory>> dataMap, Long topParentId) {
        for (Map.Entry<Long, List<TargetCategory>> entry : dataMap.entrySet()) {
            if (topParentId.equals(entry.getKey())) {
                return entry.getValue();
            }
        }
        return null;
    }

    @Deprecated
    private List<TreeDataVo> getChildrenList(Long parentId, Map<Long, List<TargetCategory>> dataMap, TreeCommonCondition condition) {
        List<TreeDataVo> resultList = Lists.newArrayList();
        for (Map.Entry<Long, List<TargetCategory>> entry : dataMap.entrySet()) {
            if (parentId.equals(entry.getKey())) {
                for (TargetCategory bean : entry.getValue()) {
                    TreeDataVo vo = new TreeDataVo(bean.getId(), bean.getCategoryName(), TreeFixedFacilityEnum.DATA_1.getCode());
                    List<TreeDataVo> childrenList = this.getChildrenList(bean.getId(), dataMap, condition);
                    if (CollectionUtils.isEmpty(childrenList)) {
                        childrenList = this.getTargetBaseInfoList(bean.getId(), condition);
                    }
                    vo.setChildren(childrenList);
                    resultList.add(vo);
                }
            }
        }
        return resultList;
    }

    @Deprecated
    private List<TreeDataVo> getTargetBaseInfoList(Long targetCategoryId, TreeCommonCondition condition) {
        List<TreeDataVo> childrenList = Lists.newArrayList();
        //查询目标类别对应的目标数据
        TargetBaseInfo targetBaseInfo = new TargetBaseInfo();
//        targetBaseInfo.setTargetCategoryId(targetCategoryId);
        targetBaseInfo.setTargetName(condition.getWords());
        List<TargetBaseInfo> targetBaseInfoList = this.selectTargetBaseInfoList(targetBaseInfo);
        if (!CollectionUtils.isEmpty(targetBaseInfoList)) {
            for (TargetBaseInfo info : targetBaseInfoList) {
                childrenList.add(new TreeDataVo(info.getId(), info.getTargetName(), TreeFixedFacilityEnum.DATA_2.getCode()));
            }
        }
        return childrenList;
    }

    @Deprecated
    public List<TargetCategory> getChildrenListDB(Long id) {
        List<TargetCategory> resultList = Lists.newArrayList();
        QueryWrapper<TargetCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<TargetCategory> dataList = targetCategoryService.list(wrapper);
        if (!CollectionUtils.isEmpty(dataList)) {
            resultList.addAll(dataList);
            for (TargetCategory bean : dataList) {
                resultList.addAll(this.getChildrenListDB(bean.getId()));
            }
        }
        return resultList;
    }
}
